package com.fablesoft.projectdatacollect.ui;

import java.io.File;

import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.fablesoft.projectdatacollect.util.StoragePathsManager;
import com.fablesoft.projectdatacollect.view.FableWebView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.LinearLayout.LayoutParams;

public class BaseWebPageActivity extends BaseRequestActivity {

	private final static String TAG = "BaseWebPageActivity";
//	protected TextView mTitleName;
	protected RelativeLayout rightView;
	protected RelativeLayout webviewLayout;
	private ImageView errorImage;
	protected ImageView rightImageView;
	private View mRetiveLeft;
	protected FableWebView mWebView;
	private ProgressBar progressBar;
	private LinearLayout webErrorLayout;
	private static final int REQUEST_CODE_IMAGE_CAPTURE = 106;
	private static final int REQUEST_CODE_PICK_IMAGE = 107;
	private ValueCallback<Uri> mUploadMsg;
	private ValueCallback<Uri[]> mUploadCallbackAboveL;
	private Intent mSourceIntent;
	// private final static int TIME_OUT_CODE = -2;
	// private boolean hasReceivedError = false;
	private String mUrl = "";
	private String title;
	private String picPath;
	private Dialog optionDialog;
	private OnClickListener selectPhotoOption;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.web_page_layout);
		Intent intent = getIntent();
		mUrl = intent.getStringExtra("url");
		title = intent.getStringExtra("title");
		initView();
		Log.i("lzx", "mUrl:" + mUrl);
//		CookieSyncManager.createInstance(this);
//		CookieManager cookieManager = CookieManager.getInstance();
//		cookieManager.setAcceptCookie(true);
//		cookieManager.removeAllCookie();
//		cookieManager.setCookie(Config.BASE, MyApplication.getInstance()
//				.getSessionId());
//		CookieSyncManager.getInstance().sync();
		mWebView.loadUrl(mUrl);
	}

	protected void initView() {
		getTitleName().setText(title);
		mRetiveLeft = getTitleBack();
		mRetiveLeft.setVisibility(View.VISIBLE);
		webErrorLayout = (LinearLayout) findViewById(R.id.web_error_tip_layout);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		errorImage = (ImageView) findViewById(R.id.base_web_error_tip_image);
		webviewLayout = (RelativeLayout) findViewById(R.id.webview_layout);
		progressBar.setProgress(1);
		mRetiveLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				backOrFinish();
			}
		});
		errorImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mWebView.stopLoading();
				webErrorLayout.setVisibility(View.GONE);
				Log.i(TAG, "loadUrlAgain");
				mWebView.reload();
			}
		});
		mWebView = (FableWebView) findViewById(R.id.webview_page);
		mWebView.setWebChromeClient(new MyWebChromeClient());
		mWebView.setWebViewClient(new MyWebViewClient());
	}
	
	@Override
	public void onBackPressed() {
		backOrFinish();
	}

	protected void backOrFinish() {
		mWebView.stopLoading();
		if (mWebView.canGoBack() && !mWebView.getUrl().equals(mUrl)) {
			mWebView.goBack();
		} else {
			finish();
		}
	}

	protected class MyWebViewClient extends WebViewClient {

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			Log.i(TAG, "onPageFinished");
			Log.i(TAG, "onPageFinished title:" + view.getTitle());
			// mHandler.removeMessages(TIME_OUT_CODE);
//			if (TextUtils.isEmpty(view.getTitle())
//					|| view.getTitle().equals("找不到网页")
//					|| view.getTitle().contains(Config.IP)) {
//				return;
//			} else {
//				mTitleName.setText(view.getTitle());
//			}
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			Log.i(TAG, "onPageStarted");
			// mHandler.removeMessages(TIME_OUT_CODE);
			// mHandler.sendEmptyMessageDelayed(TIME_OUT_CODE,
			// 30000);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			// super.onReceivedError(view, errorCode, description, failingUrl);
			Log.i("lzx", "errorCode:" + errorCode);
			Log.i("lzx", "description:" + errorCode);

			// hasReceivedError = true;
			// webErrorLayout.setVisibility(View.VISIBLE);
			// mWebView.setVisibility(View.GONE);
		}
		
//		//重写父类方法，让新打开的网页在当前的WebView中显示
//        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            view.loadUrl(url);
//            return true;
//        }
//        //扩充缓存的容量  
//        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){   
//            //handler.cancel(); 默认的处理方式，WebView变成空白页     
//            //接受证书     
//            handler.proceed();  
//        }
	}

	protected class MyWebChromeClient extends WebChromeClient {
		
        //For Android 3.0+  
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {  
        	mUploadMsg = uploadMsg;  
        	showDialog();
        }
      
      
        // For Android < 3.0  
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {  
            openFileChooser(uploadMsg, "");  
        }
      
      
        // For Android  > 4.1.1  
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {  
            openFileChooser(uploadMsg, acceptType);  
        }  
      
      
        // For Android > 5.0  
        @Override  
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams   
        fileChooserParams) {  
          mUploadCallbackAboveL = uploadMsg;
          showDialog();
          return true;  
        } 
      
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			// super.onProgressChanged(view, newProgress);
			// Log.i(TAG, "newProgress:" + newProgress);
			if (newProgress == 100) {
				// mWebView.loadUrl("javascript:window.jsObject.getHTMLSource(document.getElementsByTagName('body')[0].innerHTML);");
				// if(hasReceivedError){
				// hasReceivedError = false;
				// }else{
				// mWebView.setVisibility(View.VISIBLE);
				// }
				progressBar.setVisibility(View.INVISIBLE);
			} else {
				// mWebView.setVisibility(View.GONE);
				if (View.GONE == progressBar.getVisibility()) {
					progressBar.setVisibility(View.VISIBLE);
				}
				progressBar.setProgress(newProgress);
			}
		}
		
		//配置权限(同样在WebChromeClient中实现) 
		public void onGeolocationPermissionsShowPrompt(String origin, android.webkit.GeolocationPermissions.Callback callback) { 
			callback.invoke(origin, true, false); 
			super.onGeolocationPermissionsShowPrompt(origin, callback); 
		}
	}

	@Override  
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {  
            return;  
        }
        switch (requestCode) {
            case REQUEST_CODE_IMAGE_CAPTURE:
            	break;
            case REQUEST_CODE_PICK_IMAGE: {
                try {  
                    Uri result = data == null || resultCode != RESULT_OK ? null
    						: data.getData();
    				String[] pojo = { MediaStore.Images.Media.DATA };

    				Cursor cursor = getContentResolver().query(result, pojo, null,
    						null, null);
    				if (cursor != null) {
    					int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
    					cursor.moveToFirst();
    					picPath = cursor.getString(columnIndex);
    					cursor.close();
    					cursor = null;
    				}
                } catch (Exception e) {
					Log4jUtil.e(e.toString());
                    e.printStackTrace();  
                }  
                break;  
            }  
        }
        
        if (TextUtils.isEmpty(picPath) || !new File(picPath).exists()) {  
            Log.w(TAG, "sourcePath empty or not exists.");  
            return;  
        }
        if (mUploadMsg == null && mUploadCallbackAboveL == null) {  
            return;  
        }
        Uri uri = Uri.fromFile(new File(picPath));
        if(mUploadMsg != null){
        	 mUploadMsg.onReceiveValue(uri);
        }
        if(mUploadCallbackAboveL != null){
        	Uri[] uris = new Uri[]{uri};
        	mUploadCallbackAboveL.onReceiveValue(uris);
        }
    }
	
	public void showDialog() {
		if (optionDialog == null) {
			optionDialog = new Dialog(this, R.style.Theme_Light_CustomDialog);
			DisplayMetrics dm = getResources().getDisplayMetrics();
			int screenWidth = dm.widthPixels;
			RelativeLayout.LayoutParams RLparams = new RelativeLayout.LayoutParams(
					(int) (screenWidth * 0.6), LayoutParams.WRAP_CONTENT);
			LayoutInflater inflater = LayoutInflater.from(this);
			View v = inflater.inflate(R.layout.select_photo_layout, null);
			optionDialog.setContentView(v, RLparams);
			optionDialog.setCanceledOnTouchOutside(true);
			View takePhoto = optionDialog.findViewById(R.id.take_photo_btn);
			View pickPhoto = optionDialog.findViewById(R.id.pick_photo_btn);
			if(selectPhotoOption == null){
				selectPhotoOption = new OptionOnClickListener();
			}
			takePhoto.setOnClickListener(selectPhotoOption);
			pickPhoto.setOnClickListener(selectPhotoOption);
		}
		optionDialog.setOnCancelListener(new ReOnCancelListener());
		optionDialog.show();
	}
	
	private class OptionOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (optionDialog != null) {
				optionDialog.dismiss();
			}
			switch (v.getId()) {
			case R.id.pick_photo_btn:
				mSourceIntent = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                mSourceIntent.setType("image/*"); // 设置文件类型
                startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
				break;
			case R.id.take_photo_btn:
				StoragePathsManager mStoragePathsManager = new StoragePathsManager(
						BaseWebPageActivity.this);
				String baseDirString = "";
				if (mStoragePathsManager.ExistSDCard()) {
					baseDirString = Environment.getExternalStorageDirectory()
							.getPath()
							+ File.separator
							+ Environment.DIRECTORY_DCIM;
				} else {
					baseDirString = mStoragePathsManager
							.getInternalStoragePath();
				}
				picPath = baseDirString + "cameraImg.jpg";
				Intent mSourceIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 调用android自带的照相机
				mSourceIntent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(picPath)));
				mSourceIntent.putExtra("return-data", false);
                startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);
				break;
			}
		}
	};
	
    private class ReOnCancelListener implements DialogInterface.OnCancelListener {
        @Override  
        public void onCancel(DialogInterface dialogInterface) {  
            if (mUploadMsg != null) {  
                mUploadMsg.onReceiveValue(null); 
                mUploadMsg = null;  
            }  
            if(mUploadCallbackAboveL != null){
            	mUploadCallbackAboveL.onReceiveValue(null);
            	mUploadCallbackAboveL = null;
            }
        }
    }

    @Override
	public void onDestroy() {
		super.onDestroy();
		webviewLayout.removeView(mWebView);
		mWebView.loadUrl("about:blank");
		mWebView.stopLoading();
		mWebView.setWebChromeClient(null);
		mWebView.setWebViewClient(null);
		mWebView.destroy();
		mWebView = null;
	}
    
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
}
